using System.Collections.Generic;
using UnityEngine;

namespace LCH
{
    /// <summary>
    /// 控制图管理器 - 负责控制图的检测、管理和操作
    /// </summary>
    public class ControlTextureManager
    {
        private Setting setting;
        private Shader lastDetectedShader;
        
        // 检测结果
        public List<string> DetectedControlTextureNames { get; private set; }
        public int ControlTextureCount { get; private set; }
        public int MaxTextureCount { get; private set; }
        public bool HasFlowMap { get; private set; }
        
        public ControlTextureManager(Setting setting)
        {
            this.setting = setting;
            DetectedControlTextureNames = new List<string>();
            ControlTextureCount = 0;
            MaxTextureCount = ControlTextureConstants.DEFAULT_TEXTURE_COUNT;
            HasFlowMap = false;
        }
        
        /// <summary>
        /// 检测Shader中的控制图
        /// </summary>
        public void DetectControlTextures(Shader shader)
        {
            // 如果Shader相同，使用缓存结果
            if (shader == lastDetectedShader && DetectedControlTextureNames.Count > 0)
            {
                return;
            }
            
            DetectedControlTextureNames.Clear();
            ControlTextureCount = 0;
            HasFlowMap = false;
            lastDetectedShader = shader;
            
            if (shader == null)
            {
                ControlTextureCount = 0;
                MaxTextureCount = ControlTextureConstants.DEFAULT_TEXTURE_COUNT;
                return;
            }
            
            ScanShaderProperties(shader);
            BuildControlTextureList();
            CalculateMaxTextureCount();
        }
        
        /// <summary>
        /// 扫描Shader属性
        /// </summary>
        private void ScanShaderProperties(Shader shader)
        {
            HashSet<int> foundIndices = new HashSet<int>();
            bool foundBaseControl = false;
            
            for (int i = 0; i < shader.GetPropertyCount(); i++)
            {
                string name = shader.GetPropertyName(i);
                
                // 检查是否是基础控制图（完全匹配前缀，如 _Control）
                if (name == setting.ctrlTexturePrefix)
                {
                    foundBaseControl = true;
                }
                else if (name.StartsWith(setting.ctrlTexturePrefix))
                {
                    // 检查是否是带数字的控制图（如_Control0, _Control1）
                    string suffix = name.Substring(setting.ctrlTexturePrefix.Length);
                    if (int.TryParse(suffix, out int index))
                    {
                        foundIndices.Add(index);
                    }
                }
                
                // 检查flowmap
                if (name == setting.flowMapTextureName)
                {
                    HasFlowMap = true;
                }
            }
            
            // 构建控制图列表
            if (foundBaseControl)
            {
                DetectedControlTextureNames.Add(setting.ctrlTexturePrefix);
            }
            
            // 按索引顺序添加带数字的控制图
            List<int> sortedIndices = new List<int>(foundIndices);
            sortedIndices.Sort();
            foreach (int idx in sortedIndices)
            {
                string name = setting.ctrlTexturePrefix + idx.ToString();
                // 只有当基础_Control不存在，或者索引>=1时才添加（避免重复）
                if (!foundBaseControl || idx > 0)
                {
                    if (!DetectedControlTextureNames.Contains(name))
                    {
                        DetectedControlTextureNames.Add(name);
                    }
                }
            }
        }
        
        /// <summary>
        /// 构建控制图列表（已合并到ScanShaderProperties中，保留用于扩展）
        /// </summary>
        private void BuildControlTextureList()
        {
            ControlTextureCount = DetectedControlTextureNames.Count;
        }
        
        /// <summary>
        /// 计算最大贴图数量
        /// </summary>
        private void CalculateMaxTextureCount()
        {
            // 每张控制图4个通道（RGBA），flowmap在最后一张的Alpha通道
            MaxTextureCount = ControlTextureCount * ControlTextureConstants.CHANNELS_PER_CONTROL_TEXTURE;
            
            // 限制最大数量
            if (MaxTextureCount > ControlTextureConstants.MAX_TEXTURE_COUNT)
                MaxTextureCount = ControlTextureConstants.MAX_TEXTURE_COUNT;
        }
        
        /// <summary>
        /// 获取指定索引的控制图名称
        /// </summary>
        public string GetControlTextureName(int index)
        {
            if (IsValidIndex(index))
            {
                return DetectedControlTextureNames[index];
            }
            return null;
        }
        
        /// <summary>
        /// 根据索引生成控制图名称（用于创建新控制图）
        /// </summary>
        public string GenerateControlTextureName(int index)
        {
            if (index == 0)
            {
                return setting.ctrlTexturePrefix;
            }
            return setting.ctrlTexturePrefix + index.ToString();
        }
        
        /// <summary>
        /// 验证索引是否有效
        /// </summary>
        public bool IsValidIndex(int index)
        {
            return index >= 0 && index < ControlTextureCount && index < DetectedControlTextureNames.Count;
        }
        
        /// <summary>
        /// 根据编辑通道计算控制图索引和通道索引
        /// </summary>
        public void CalculateEditingIndices(int editingChannel, out int ctrlIndex, out int channelIndex)
        {
            ctrlIndex = editingChannel / ControlTextureConstants.CHANNELS_PER_CONTROL_TEXTURE;
            channelIndex = editingChannel % ControlTextureConstants.CHANNELS_PER_CONTROL_TEXTURE;
            
            // 确保索引有效
            if (ctrlIndex >= ControlTextureCount)
                ctrlIndex = ControlTextureCount - 1;
            if (ctrlIndex < 0)
                ctrlIndex = 0;
        }
        
        /// <summary>
        /// 清除检测缓存（当Shader改变时调用）
        /// </summary>
        public void ClearCache()
        {
            lastDetectedShader = null;
            DetectedControlTextureNames.Clear();
            ControlTextureCount = 0;
            MaxTextureCount = ControlTextureConstants.DEFAULT_TEXTURE_COUNT;
            HasFlowMap = false;
        }
    }
}

